package com.meixiang.fragment.fund;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.R;
import com.meixiang.activity.WebviewActivity;
import com.meixiang.activity.account.myfund.FundDetialActivity;
import com.meixiang.activity.account.myfund.FundLoginWebViewActivity;
import com.meixiang.activity.account.myfund.MyFundActivity;
import com.meixiang.adapter.myFundAdapter.FundHoldAdapter;
import com.meixiang.dialog.HoldHistoryPopup;
import com.meixiang.dialog.LoadingDialog;
import com.meixiang.entity.fund.FundAccountResult;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;


import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 持有基金
 * Created by xyj on 2016/5/31.
 */
public class HoldFragment extends BaseFragment implements View.OnClickListener, OnRefreshListener {
    private static final int REQUEST_CODE = 1 ;
    @Bind(R.id.swipe_target)
    RecyclerView mRecycler;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mLayout;
    @Bind(R.id.top_view)
    View top_view;
    @Bind(R.id.tv_fund_history_hold)
    LinearLayout tv_fund_history_hold; //查看历史基金
    @Bind(R.id.tv_fund_no_data)
    TextView tv_fund_no_data; //暂无持有基金数据
    private View headView;
    private FundHoldAdapter mFundAdapter;
    private FundAccountResult fundAccountResult; //持有基金数据
    private Context context;
    private HoldHistoryPopup holdHistoryPopup;
    private View rootView;
    private TextView tv_fund_money, tv_confirmed_money, tv_profit_loss, tv_total_profit_loss, tv_profit_loss_hint, total_profit_loss_hint; //总金额 、待确认金额、昨日盈亏、累计盈亏
    private int page = 1;
    private int pageSize = 10;
    private LoadingDialog loadingDialog;
    private boolean isRefresh = false ;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_hold_content, container, false);
        ButterKnife.bind(this, rootView);
        context = getActivity();
        return rootView;
    }

    @Override
    protected void initTitle() {

    }

    @Override
    protected void initView() {
        headView = LayoutInflater.from(context).inflate(R.layout.fund_hold_head_view, null);
        tv_fund_money = (TextView) headView.findViewById(R.id.tv_fund_money);
        tv_confirmed_money = (TextView) headView.findViewById(R.id.tv_confirmed_money);
        tv_profit_loss = (TextView) headView.findViewById(R.id.tv_profit_loss);
        tv_total_profit_loss = (TextView) headView.findViewById(R.id.tv_total_profit_loss);
        tv_profit_loss_hint = (TextView) headView.findViewById(R.id.tv_profit_loss_hint);
        total_profit_loss_hint = (TextView) headView.findViewById(R.id.total_profit_loss_hint);
        tv_fund_history_hold.setOnClickListener(this);
        total_profit_loss_hint.setOnClickListener(this);
        mLayout.setOnRefreshListener(this);
        mLayout.setLoadMoreEnabled(false);
    }

    @Override
    protected void setData() {
        loadingDialog = new LoadingDialog(getContext());
        initFundData();
        getHttpFundData();
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        mRecycler.setLayoutManager(mLayoutManager);
        mRecycler.setItemAnimator(new DefaultItemAnimator());
        mRecycler.setLayoutManager(mLayoutManager);
    }

    /**
     * 填充Adapter
     */
    private void initFundData() {
        mFundAdapter = new FundHoldAdapter(context);
        mRecycler.setAdapter(mFundAdapter);
        mFundAdapter.setHeaderView(headView);
        mFundAdapter.setOnItemClickListener(new FundHoldAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(context, FundDetialActivity.class);
                intent.putExtra("id", fundAccountResult.getData().getFund_holding_list().get(position).getId());
                intent.putExtra("titleName", fundAccountResult.getData().getFund_holding_list().get(position).getFund_name());
                intent.putExtra("fund_id", fundAccountResult.getData().getFund_holding_list().get(position).getFund_id());
                context.startActivity(intent);
            }
        });
    }

    private void initHeaderView() {
        tv_fund_money.setText(AbStrUtil.ChangeF3D(fundAccountResult.getData().getTrade_total_money()));
        tv_confirmed_money.setText(AbStrUtil.ChangeF3D(fundAccountResult.getData().getUnderway_amount_all()));
        if(fundAccountResult.getData().getFlow_profit_yesterday().contains("-")){
            tv_profit_loss.setText(AbStrUtil.ChangeF3D(fundAccountResult.getData().getFlow_profit_yesterday()));
        }else{
            tv_profit_loss.setText("+"+AbStrUtil.ChangeF3D(fundAccountResult.getData().getFlow_profit_yesterday()));
        }
        tv_profit_loss_hint.setText(fundAccountResult.getData().getFlow_profit_yesterday_name()+":");
        if(fundAccountResult.getData().getFlow_profit_all().contains("-")){
            tv_total_profit_loss.setText(AbStrUtil.ChangeF3D(fundAccountResult.getData().getFlow_profit_all()));
        }else{
            tv_total_profit_loss.setText("+"+AbStrUtil.ChangeF3D(fundAccountResult.getData().getFlow_profit_all()));
        }
        total_profit_loss_hint.setText(fundAccountResult.getData().getFlow_profit_all_name()+":");
    }

    /**
     * 获取我的持有基金数据
     * fundSessionId 我的基金sessionId
     */
    private void getHttpFundData() {
        HttpParams params = new HttpParams();
        params.put("page", String.valueOf(page));
        params.put("pageSize", String.valueOf(pageSize));
        HttpUtils.post(Config.FUND_ACCOUNT, MyFundActivity.TAG,params,new HttpCallBack(activity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                fundAccountResult = AbJsonUtil.fromJson(result.toString(), new TypeToken<FundAccountResult>() {
                });
                if (fundAccountResult != null && fundAccountResult.getData().getFund_holding_list() != null) {
                    mFundAdapter.refreshData(fundAccountResult.getData().getFund_holding_list());
                    initHeaderView();
                    if(isRefresh){
                        mLayout.setRefreshing(false);
                    }
                }
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                if (loadingDialog != null && loadingDialog.isShowing())
                    loadingDialog.dismiss();
            }

            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                if (loadingDialog != null && !loadingDialog.isShowing())
                    loadingDialog.show();
            }

            @Override
            public void onError(String code, String message) {
                if ("-2".equals(code)) {// 表示未登录 需要跳转到口袋登录页面
                    getHttpToLogin();
                }
            }
        });
    }

    /***
     * toLogin 跳转登录或者注册界面API
     * url 回调地址
     */
    private void getHttpToLogin() {
        HttpParams params = new HttpParams();
        params.put("url", Config.CALLBACK_URL);
        HttpUtils.post(Config.FUND_TOLOGIN,MyFundActivity.TAG,params, new HttpCallBack(activity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Intent intent = new Intent(context, WebviewActivity.class);
                intent.putExtra("url", result.optString("url"));
                intent.putExtra("title", "口袋登录");
                startActivityForResult(intent, REQUEST_CODE);
            }

            @Override
            public void onError(String code, String message) {

            }
        });
    }

    /**
     * 主要为了获取fundSessionId ;获取成功则重新访问我的基金接口
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE){
            getHttpFundData();
        }
    }

    private void initPupopWindow() {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_hold_history_view, null);
        holdHistoryPopup = new HoldHistoryPopup(context, view, getActivity());
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.tv_fund_history_hold:
                initPupopWindow();
                if (holdHistoryPopup.isShowing()) {
                    holdHistoryPopup.dismiss();
                } else {
                    holdHistoryPopup.showAsDropDown(top_view);
                }
                break;
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        isRefresh = true ;
        getHttpFundData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
